// 时间格式化自定义库
// cch
// 2019年10月30日9:14:0

function friendlyDate(timestamp) {
	var formats = {
		'year': '%n% 年前',
		'month': '%n% 月前',
		'day': '%n% 天前',
		'hour': '%n% 小时前',
		'minute': '%n% 分钟前',
		'second': '%n% 秒前',
	};
	var now = Date.now();
	var seconds = Math.floor((now - timestamp) / 1000);
	var minutes = Math.floor(seconds / 60);
	var hours = Math.floor(minutes / 60);
	var days = Math.floor(hours / 24);
	var months = Math.floor(days / 30);
	var years = Math.floor(months / 12);

	var diffType = '';
	var diffValue = 0;
	if (years > 0) {
		diffType = 'year';
		diffValue = years;
	} else {
		if (months > 0) {
			diffType = 'month';
			diffValue = months;
		} else {
			if (days > 0) {
				diffType = 'day';
				diffValue = days;
			} else {
				if (hours > 0) {
					diffType = 'hour';
					diffValue = hours;
				} else {
					if (minutes > 0) {
						diffType = 'minute';
						diffValue = minutes;
					} else {
						diffType = 'second';
						diffValue = seconds === 0 ? (seconds = 1) : seconds;
					}
				}
			}
		}
	}
	return formats[diffType].replace('%n%', diffValue);
}






function Date_A(ee) {
	// 时间"2018-07-09 14:13:11"得到毫秒数"1531116791000"
	var startDate = ee.replace(new RegExp("-", "gm"), "/");
	var eM = (new Date(startDate)).getTime(); //得到毫秒数
	startDate = undefined;
	startDate = null;
	//console.log('Date_A--ok');
	return eM;
}

function Date_B(dd) {
	// 毫秒数"1531116791000"得到时间2018-07-09 14:13:11"
	var d = new Date(dd); //得到普通的时间
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());
	var second = change(d.getSeconds());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	d = null;
	year = null;
	month = null;
	day = null;
	hour = null;
	minute = null;
	second = null;
	return time;
	second = null;
}



function Date_E(dd) {
	// 毫秒数"1531116791000"得到时间2018-07-09 14:13:11"
	var d = new Date(dd); //得到普通的时间
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day;
	d = null;
	year = null;
	month = null;
	day = null;
	return time;
}

function Date_EE(dd) {
	// 毫秒数"1531116791000"得到时间2018-07-09 14:13"
	var d = new Date(dd); //得到普通的时间
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
	d = null;
	year = null;
	month = null;
	day = null;
	hour = null;
	minute = null;
	return time;
}


function Date_C() {
	// 返回当前时间"2018-07-09 14:13:11"
	var d = new Date();
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());
	var second = change(d.getSeconds());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
	/* console.log(d);
	console.log(time); */
	return time;
}

function Date_D() {
	// 返回当前时间"2018-07-09"
	var d = new Date();
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());
	var second = change(d.getSeconds());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day;
	/* console.log(d);
	console.log(time); */
	return time;
}


function Date_F(dd) {
	// 返回当前时间"2018-07-09 15:11"
	var d = new Date(dd);
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());
	var second = change(d.getSeconds());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year + '-' + month + '-' + day + ' ' + hour + ':' + minute;
	/* console.log(d);
	console.log(time); */
	return time;
}

//格式化日期
//06-20 17:30
function formatTime(inputTime) {
	if (inputTime.indexOf("-") != -1 && inputTime.indexOf(" ") != -1) {
		let Temp = inputTime.split(' '); //2022-06-20 17:20:31
		let part1 = Temp[0].split('-')[1] + "-" + Temp[0].split('-')[2]; //06-20
		let part2 = Temp[1].split(':')[0] + ":" + Temp[1].split(':')[1]; //17:20
		return part1 + " " + part2;
	}
	return inputTime;
}


//中文时间 dateStr: 2022-08-07 return: 2022年08月07日
function ChineseDate(dateStr) {
	if (dateStr.indexOf("-") != -1) {
		let year = dateStr.split("-")[0];
		let month = dateStr.split("-")[1];
		let day = dateStr.split("-")[2];
		return year + "年" + month + "月" + day + "日";
	}
	return dateStr;
}

//中文时间 dateStr: 2022-10-10 return: 2022年10月
function ChineseDateII(dateStr) {
	if (dateStr.indexOf("-") != -1) {
		let year = dateStr.split("-")[0];
		let month = dateStr.split("-")[1];
		return year + "年" + month + "月";
	}
	return dateStr;
}




//1663494399 返回 2022年08月07日
function timestampToFormat(timestamp) {
	timestamp = timestamp + "";
	if (timestamp.length < 13) timestamp = parseInt(timestamp) * 1000;
	var datestr = Date_E(timestamp);
	//console.log("时间字符:",ChineseDate(datestr));
	return ChineseDate(datestr);
}

//1663494399 返回 2022-08-07
function timetampToDate(timestamp) {
	timestamp = timestamp + "";
	if (timestamp.length < 13) timestamp = parseInt(timestamp) * 1000;
	var datestr = Date_E(timestamp);
	//console.log("时间字符:",ChineseDate(datestr));
	return ChineseDate(datestr);
}


//2022-3-2 返回 2022-03-02
function formatYMD(inputDate) {
	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	if (inputDate.indexOf("-") != -1) {
		let arrDate = inputDate.split("-");
		let year = arrDate[0];
		let month = change(parseInt(arrDate[1]));
		let day = change(parseInt(arrDate[2]));
		return year + "-" + month + "-" + day;
	}
	return inputDate;
}







//判断昨天、今天、明天
function isToday(str) {
	let d = new Date(str).setHours(0, 0, 0, 0);
	let today = new Date().setHours(0, 0, 0, 0);

	let obj = {
		'-86400000': '昨天',
		0: '今天',
		86400000: '明天',
	};
	return obj[d - today] || '啥也不是';
};




function randomString(len) {
	var len = len || 32;
	var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
	var maxPos = $chars.length;
	var pwd = '';
	for (var i = 0; i < len; i++) {
		pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
	}
	return pwd;
}




function GenerateOrderNo() {
	// 返回当前时间"2018-07-09 14:13:11"
	var d = new Date();
	var year = d.getFullYear();
	var month = change(d.getMonth() + 1);
	var day = change(d.getDate());
	var hour = change(d.getHours());
	var minute = change(d.getMinutes());
	var second = change(d.getSeconds());

	function change(t) {
		if (t < 10) {
			return "0" + t;
		} else {
			return t;
		}
	}
	var time = year.toString() + month.toString() + day.toString() + hour.toString() + minute.toString() + second
		.toString();
	return time;
}





//检查2个日期值
/*a=开始时间,b=结束时间*/
function duibi(a, b) {
	var arr = a.split("-");
	var starttime = new Date(arr[0], arr[1], arr[2]);
	var starttimes = starttime.getTime();

	var arrs = b.split("-");
	var lktime = new Date(arrs[0], arrs[1], arrs[2]);
	var lktimes = lktime.getTime();

	if (starttimes > lktimes) {
		//alert('日期选择错误\n不能选择比'+a+'更早的日期');
		return false;
	} else
		return true;
}
//检查2个日期值
/*a=今日的日期,b=输入的时间*/
function CheckToday(a, b) {
	var arr = a.split("-");
	var starttime = new Date(arr[0], arr[1], arr[2]);
	var starttimes = starttime.getTime();

	var arrs = b.split("-");
	var lktime = new Date(arrs[0], arrs[1], arrs[2]);
	var lktimes = lktime.getTime();

	if (starttimes > lktimes) {
		//alert('起始日时间选择错误！\n 今天是'+a);
		return false;
	} else
		return true;
}
//检查2个日期值
/*a=起始时间,b=结束时间*/
function CheckStartAndEnd(a, b) {
	var arr = a.split("-");
	var starttime = new Date(arr[0], arr[1], arr[2]);
	var starttimes = starttime.getTime();

	var arrs = b.split("-");
	var lktime = new Date(arrs[0], arrs[1], arrs[2]);
	var lktimes = lktime.getTime();
	if ((starttimes - lktimes) > 0) {
		//alert('结束时间不能比开始时间'+a+'更早');
		return false;
	} else
		return true;
}

//检查2个日期值是否相等
/*a=起始时间,b=结束时间*/
function EqualDay(a, b) {
	var arr = a.split("-");
	var starttime = new Date(arr[0], arr[1], arr[2]);
	var starttimes = starttime.getTime();

	var arrs = b.split("-");
	var lktime = new Date(arrs[0], arrs[1], arrs[2]);
	var lktimes = lktime.getTime();

	if (starttimes === lktimes) {
		return true;
	} else {
		return false;
	}
}
//检查起始日期，是否超出指定范围的日期
/*a=起始时间,b=最大时间*/
function MaxDay(a, b) {
	var arr = a.split("-");
	var starttime = new Date(arr[0], arr[1], arr[2]);
	var starttimes = starttime.getTime();

	var arrs = b.split("-");
	var lktime = new Date(arrs[0], arrs[1], arrs[2]);
	var lktimes = lktime.getTime();

	if (starttimes > lktimes) {
		return true;
	} else {
		return false;
	}
}


//计算2个日期差值
//要将日期的-变换为 /
function GetDiffTime(a, b, flag) {
	//alert(a.replace(/(\b-\b)/g,"/")+","+b.replace(/(\b-\b)/g,"/"));
	var date1 = new Date(a.replace(/(\b-\b)/g, "/"));
	var date2 = new Date(b.replace(/(\b-\b)/g, "/"));
	var s1 = date1.getTime();
	var s2 = date2.getTime();
	var total = (s2 - s1) / 1000;
	var day = parseInt(total / (24 * 60 * 60)); //计算整数天数
	var afterDay = total - day * 24 * 60 * 60; //取得算出天数后剩余的秒数
	var hour = parseInt(afterDay / (60 * 60)); //计算整数小时数
	var afterHour = total - day * 24 * 60 * 60 - hour * 60 * 60; //取得算出小时数后剩余的秒数
	var min = parseInt(afterHour / 60); //计算整数分
	var afterMin = total - day * 24 * 60 * 60 - hour * 60 * 60 - min * 60; //取得算出分后剩余的秒数    

	if (flag === "大小") {
		return (s2 > s1) ? true : false;
	}
	if (flag === "日") {
		return day;
	}
	if (flag === "时") {
		return hour;
	}
	if (flag === "分") {
		return min;
	}
}


//毫秒转分钟
function millisecondToMinute(millisecond) {
	return parseInt(millisecond / 1000 / 60);
}
//毫秒转小时
function millisecondToHour(millisecond) {
	return parseInt(millisecond / 1000 / 60 / 60);
}
//毫秒转天数
function millisecondToDay(millisecond) {
	return parseInt(millisecond / 1000 / 60 / 60 / 24);
}


function getweek() {
	var now = new Date();
	var h = now.getDay() - 1;
	var we = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
	console.log(we[h])
	return we[h]
}

function getweek_II() {
	var now = new Date();
	var h = now.getDay() - 1;
	var we = ['一', '二', '三', '四', '五', '六', '日']
	console.log(we[h])
	return we[h]
}


//判断年份是闰年还是平年
function isLeap(yy) {
	var isrun = (yy % 100 == 0 && yy % 400 == 0) || (yy % 100 != 0 && yy % 4 == 0) ? true : false;
	return isrun;
}

//获取当前月份总天数
function GetMonthDays(year, month) {
	var d = new Date(year, month, 0);
	return d.getDate();
}



//获取一周内的几天
//Step.js? [sm]:695 一周的天数: 2021/7/15,2021/7/14,2021/7/13,2021/7/12,2021/7/11,2021/7/10,2021/7/9
function GetWeekDays() {
	const DAYS = 7;
	var weeks = ''
	for (var i = 0; i < DAYS; i++) {
		var day = (new Date()).getTime() - 1000 * 3600 * 24 * i
		var Y = new Date(day).getFullYear();
		var M = new Date(day).getMonth() + 1;
		if (M > 12) M = 1;
		var D = new Date(day).getDate();
		//weeks +=new Date(day).toLocaleDateString().replace(/\//img,"-")+","; //这种方式在不同手机端，显示格式会不一样
		weeks += Y + "-" + M + "-" + D + ",";
	}
	return weeks.substring(0, weeks.length - 1);
}

//根据当天星期几，计算出之前的几天
function GetWeekDays_II(num) {
	var weeks = ''
	for (var i = 1; i < num + 1; i++) {
		var day = (new Date()).getTime() - 1000 * 3600 * 24 * i
		var Y = new Date(day).getFullYear();
		var M = new Date(day).getMonth() + 1;
		if (M > 12) M = 1;
		M = (M < 10) ? "0" + M : M;
		var D = new Date(day).getDate();
		D = (D < 10) ? "0" + D : D;
		//weeks +=new Date(day).toLocaleDateString().replace(/\//img,"-")+","; //这种方式在不同手机端，显示格式会不一样
		weeks += Y + "-" + M + "-" + D + ",";
	}
	return weeks.substring(0, weeks.length - 1);
}



//根据当天星期几，计算出之前的几号
function GetWeekDays_III(num, act) {
	var days = ''
	if (act === '日期前') {
		if (num <= 0) {
			num = 6;
		} else {
			num = 7 - num;
		}
		for (var i = 1; i < 6; i++) {
			var day = (new Date()).getTime() - 1000 * 3600 * 24 * i
			var D = new Date(day).getDate();
			days += D + ",";
		}
	}
	if (act === '日期后') {
		if (num <= 0) {
			num = 6;
		} else {
			num = 6 - num;
		}
		for (var i = 1; i < num + 1; i++) {
			var day = (new Date()).getTime() + 1000 * 3600 * 24 * i
			var D = new Date(day).getDate();
			days += D + ",";
		}
	}
	return days.substring(0, days.length - 1);
}






//根据星期几，获取当前是月份中的几号
/*
// 使用示例：获取今天是星期几（0-6）
const weekday = new Date().getDay();
console.log(`今天是第${getTodayNumberByWeekday(weekday)}号`);
*/
function getTodayNumberByWeekday(weekday) {
  const today = new Date();
  const todayWeekday = today.getDay(); // 0-6 表示星期日至星期六
  let dayOfMonth = today.getDate(); // 获取当前日
 
  if (weekday === todayWeekday) {
    return dayOfMonth;
  }
 
  // 计算差值
  let diff = weekday - todayWeekday;
  if (weekday < todayWeekday) {
    diff += 7;
  }
 
  // 创建新日期对象以获取下个星期指定的日子
  const nextWeek = new Date(today.getFullYear(), today.getMonth(), dayOfMonth + diff);
  return nextWeek.getDate();
}


export {
	friendlyDate,
	Date_A,
	Date_B,
	Date_C,
	Date_D,
	Date_E,
	Date_EE,
	Date_F,
	getweek_II,
	randomString,
	duibi,
	CheckToday,
	CheckStartAndEnd,
	EqualDay,
	MaxDay,
	GetDiffTime,
	millisecondToMinute,
	millisecondToHour,
	millisecondToDay,
	GenerateOrderNo,
	getweek,
	isLeap,
	GetMonthDays,
	GetWeekDays,
	GetWeekDays_II,
	GetWeekDays_III,
	formatTime,
	ChineseDate,
	ChineseDateII,
	timestampToFormat,
	formatYMD,
	isToday,
	timetampToDate,
	getTodayNumberByWeekday
}